﻿

$(function () {

    //左侧栏 自定义滚动条
    $(".sideBarCont").mCustomScrollbar({ 'scrollbarPosition': 'outside', 'autoHideScrollbar': true, scrollInertia: 100 });
    ////内容区域 自定义滚动条
    $(".mainCont").mCustomScrollbar({ 'scrollbarPosition': 'outside', 'autoHideScrollbar': true, scrollInertia: 100, 'callbacks': { onScrollStart: function () { $('.ui-autocomplete').hide(); } } });
})

function ProcessAjaxRequest(url, method, data, successmethod) {
    $.ajax({
        url: url,
        type: method,
        data: data,
        success: function (data) {
            successmethod(data);
        },
        error: function (err) {
            if (err.status == "401") {
                AlertErrorBox("当前用户未登录，或登录已超时");
            } else {
                AlertErrorBox("处理请求失败");
            }
        }
    })
}


function moneyIpt(obj) {
    var _this = $(obj),
        _val = _this.val(),
        _reg = /^\d*((\.{0,1})(\d+))$/;
    if (_reg.test(_val)) {
        if (/\./.test(_val)) {
            var numA = _val.split('.');

        }
    } else {
        alert('请输入有效金额');
    }

}

function fmoney(s, n) {
    n = n > 0 && n <= 20 ? n : 2;
    s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
    var l = s.split(".")[0].split("").reverse(),
    r = s.split(".")[1];
    t = "";
    for (i = 0; i < l.length; i++) {
        t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");
    }
    return t.split("").reverse().join("") + "." + r;
}

function rmoney(s) {
    return parseFloat(s.replace(/[^\d\.-]/g, ""));
}

//table等分
function AverT() {

    var _t = $('.averT');

    _t.each(function () {
        var _firstRowTd = $(this).find('tr:eq(0)').children('td'),
            _ratio = 100 / _firstRowTd.length + '%';
        _firstRowTd.each(function () {
            $(this).attr('width', _ratio);
        });
    })


}

function getUrlParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    var r = window.location.search.substr(1).match(reg);  //匹配目标参数
    if (r != null) return unescape(r[2]); return null; //返回参数值
}
function getUrlpath() {
    return window.location.pathname;
}

/**
 * 随机生成N位随机数   modify by nls
 * @param {} n 随机数的位数
 * @returns {} 
 */
function RndNum(n) {
    var rnd = "";
    for (var i = 0; i < n; i++)
        rnd += Math.floor(Math.random() * 10);
    return rnd;
}

/*
用途：判断是否是日期                add by nls
输入：date：日期；fmt：日期格式
返回：如果通过验证返回true,否则返回false
*/
function isDate(date, fmt) {
    if (fmt == null) fmt = "yyyyMMdd";
    var yIndex = fmt.indexOf("yyyy");
    if (yIndex == -1) return false;
    var year = date.substring(yIndex, yIndex + 4);
    var mIndex = fmt.indexOf("MM");
    if (mIndex == -1) return false;
    var month = date.substring(mIndex, mIndex + 2);
    var dIndex = fmt.indexOf("dd");
    if (dIndex == -1) return false;
    var day = date.substring(dIndex, dIndex + 2);
    if (!isNumber(year) || year > "2100" || year < "1900") return false;
    if (!isNumber(month) || month > "12" || month < "01") return false;
    if (day > getMaxDay(year, month) || day < "01") return false;
    return true;
}
function getMaxDay(year, month) {
    if (month == 4 || month == 6 || month == 9 || month == 11)
        return "30";
    if (month == 2)
        if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0)
            return "29";
        else
            return "28";
    return "31";
}
/*
用途：检查输入字符串是否符合正整数格式    add by nls
输入：
s：字符串
返回：
如果通过验证返回true,否则返回false
*/
function isNumber(s) {
    var regu = "^[0-9]+$";
    var re = new RegExp(regu);
    if (s.search(re) != -1) {
        return true;
    } else {
        return false;
    }
}
/*
用途：检查输入字符串是否只由英文字母和数字组成
输入：
s：字符串
txtid:输入框id
lbid:校验信息提示label
返回：
如果通过验证返回true,否则返回false
*/
function isNumberOrLetter(s, lbid, txtid) {//判断是否是数字或字母
    var txtobj = $("#" + txtid);
    var flag = true;
    var regu = "^[0-9a-zA-Z]+$";
    var re = new RegExp(regu);
    if (s == "") {
        txtobj.showError();
        flag = false;
    } else {
        if (re.test(s)) {
            txtobj.hideError();
        } else {
            flag = false;
        }
    }
    return flag;
}


/*
 * fomateDate Function
 */
Date.prototype.format = function (format) //author: meizz
{
    var o = {
        "M+": this.getMonth() + 1, //month
        "d+": this.getDate(),    //day
        "h+": this.getHours(),   //hour
        "m+": this.getMinutes(), //minute
        "s+": this.getSeconds(), //second
        "q+": Math.floor((this.getMonth() + 3) / 3),  //quarter
        "S": this.getMilliseconds() //millisecond
    }
    if (/(y+)/.test(format)) format = format.replace(RegExp.$1,
    (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o) if (new RegExp("(" + k + ")").test(format))
        format = format.replace(RegExp.$1,
      RegExp.$1.length == 1 ? o[k] :
        ("00" + o[k]).substr(("" + o[k]).length));
    return format;
}
function formatTime(val) {
    var re = /-?\d+/;
    var m = re.exec(val);
    var d = new Date(parseInt(m[0]));
    // 按【2012-02-13 09:09:09】的格式返回日期
    return d.format("yyyy-MM-dd hh:mm:ss");
}

function formatDate(val) {
    var re = /-?\d+/;
    var m = re.exec(val);
    var d = new Date(parseInt(m[0]));
    // 按【2012-02-13 09:09:09】的格式返回日期
    return d.format("yyyy-MM-dd");
}
//json日期格式转换为正常格式
function jsonDateFormat(jsonDate) {
    try {
        var date = new Date(parseInt(jsonDate.replace("/Date(", "").replace(")/", ""), 10));
        var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
        var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
        var hours = date.getHours();
        var minutes = date.getMinutes();
        var seconds = date.getSeconds();
        var milliseconds = date.getMilliseconds();
        //return date.getFullYear() + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds + "." + milliseconds;
        return date.getFullYear() + "年" + month + "月" + day + " 日";
    } catch (ex) {
        return "";
    }
}

/** 
 * 获取当前年月日及时间精确到秒  modify by nls 
 *modify by chris
 * @returns {} "2015-10-20 16:01:12"
 */
function GetDateTimeNow() {
    var now = new Date();
    var year = now.getFullYear(); //年
    var month = now.getMonth() + 1; //月
    var day = now.getDate(); //日
    var hh = now.getHours(); //时
    var mm = now.getMinutes(); //分
    var ss = now.getSeconds() //秒
    var clock = year + "-";
    if (month < 10)
        clock += "0";
    clock += month + "-";
    if (day < 10)
        clock += "0";
    clock += day + " ";
    if (hh < 10)
        clock += "0";
    clock += hh + ":";
    if (mm < 10) clock += '0';
    clock += mm + ":";
    if (ss < 10) clock += '0';
    clock += ss;
    return (clock);
}

/** 
 * 获取当前年月日  modify by nls
 * @returns {} "2015-10-20"
 */
function GetDateNow() {
    var now = new Date();
    var year = now.getFullYear(); //年
    var month = now.getMonth() + 1; //月
    var day = now.getDate(); //日
    var clock = year + "-";
    if (month < 10)
        clock += "0";
    clock += month + "-";
    if (day < 10)
        clock += "0";
    clock += day + "";
    return (clock);
}


/**
 * 检查是否是手机号码   modify by nls
 * @param {} val 11位手机号码
 * @returns {} true/false
 */
function checkisMobile(val) {
    return /^1((([34578])\d{9})|(47\d{8}))$/.test(val);
}
/**
 * 检查是否是手机号码   modify by nls
 * @param {} val 010-12345678
 * @returns {} true/false
 */
function checkisTel(val) {
    return /^\d{3,4}-?\d{7,9}$/.test(val);
}
/**
 * 检查联系电话(手机/电话皆可)验证   modify by nls
 * @param {} val 010-12345678或11位手机号码
 * @returns {} true/false
 */
function checkisPhone(val) {
    return checkisTel(val);
}

/**
 * 检查是否是中文名称   modify by nls
 * @param {} val 文本框内容
 * @returns {} true/false
 */
function checkiscnname(val) {
    //首先去掉首末位空格
    var str = val.replace(/(^\s*)|(\s*$)/g, "");
    return /^[\u4e00-\u9fa5]+$/.test(str);
}

/**
 * 检查是否是英文名称   modify by nls
 * @param {} val 文本框内容
 * @returns {} true/false
 */
function checkisenname(val) {
    //首先去掉首末位空格
    var str = val.replace(/(^\s*)|(\s*$)/g, "");
    return /^[A-Za-z][A-Za-z\s]*[A-Za-z]$/.test(str);;
}

$.fn.showError = function () {
    $(this).addClass("error");
};

$.fn.hideError = function () {
    $(this).removeClass("error");
};

$.fn.showFontError = function () {
    $(this).css("color", "red");
};

$.fn.hideFontError = function () {
    $(this).css("color", "black");
};



/*
 * 根据长度截取先使用字符串，超长部分追加...   modify by nls
 * 参数说明：
 * str 对象字符串
 * len 目标字节长度
 * 返回值： 处理结果字符串
 * 汉字、全角符号按2个占位，数字英文、半角按一个占位
 */
function cutString(str, len) {
    //length属性读出来的汉字长度为1
    var temp1 = str.replace(/[^\x00-\xff]/g, "**");//正则替换
    var temp2 = temp1.substring(0, len);
    //找出有多少个*
    var x_length = temp2.split("\*").length - 1;
    var hanzi_num = x_length / 2;
    len = len - hanzi_num;//实际需要sub的长度是总长度-汉字长度
    var res = str.substring(0, len);
    if (len < str.length) {
        var endstr = res + "...";
    } else {
        var endstr = res;
    }
    return endstr;
}


/**
 * 检查是否为空或undefined并返回值或默认值    modify by nls
 * @param {} pval 需要检查的字符串
 * @param {} type 字符串类型  int str bool time2 time float
 * @returns {} 返回值或默认值
 */
function checkemptyval(pval, type) {
    if (pval == "" || pval == "undefined" || typeof (pval) == "undefined") {
        switch (type) {
            case "bool":
                return false;
            case "str":
                return '';
            case "int":
                return 0;
            case "time":
                return '1900/01/01 0:00:00';
                //return GetDateTimeNow();
            case "time2":
                return '07:00';
            case "float":
                return 0;
        }
    } else {
        switch (type) {
            case "int":
                return parseInt(pval);
            case "bool":
                if (parseInt(pval) > 0) {
                    return true;
                } else {
                    return false;
                }
            case "float":
                return parseFloat(pval).toFixed(2);
            default:
                return pval;
        }
    }
}

if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function (elt /*, from*/) {
        var len = this.length >>> 0;
        var from = Number(arguments[1]) || 0;
        from = (from < 0)
             ? Math.ceil(from)
             : Math.floor(from);
        if (from < 0)
            from += len;
        for (; from < len; from++) {
            if (from in this &&
                this[from] === elt)
                return from;
        }
        return -1;
    };
}


function Loading() {
    var o = layer.load(1, {
        shade: [0.1, '#fff'] //0.1透明度的白色背景
    });
    return o;
}

/**
 * alert Warn box modify by nls 
 * @param {} content 
 */
function AlertWarnBox(content) {
    if (content == "" || typeof (content) == "undefined") {
        content = "Error";
    }
    layer.msg(content, {
        skin: 'layui-layer-lan',
        offset: 'auto',
        shift: 6,
        icon: 7
    });
}

/**
 * alert Complete box modify by nls 
 * @param {} content 
 */
function AlertCompleteBox(content) {
    if (content == "" || typeof (content) == "undefined") {
        content = "Complete";
    }
    layer.msg(content, { icon: 6 });
}

/**
 * alert Error box modify by nls 
 * @param {} content 
 */
function AlertErrorBox(content) {
    if (content == "" || typeof (content) == "undefined") {
        content = "Error";
    }
    layer.msg(content, { icon: 2 });
}

/**
 * alert Error box modify by nls 
 * @param {} content 
 */
function AlertUserWarnBox(content) {
    if (content == "" || typeof (content) == "undefined") {
        content = "Error";
    }
    layer.open({
        type: 1, //page层
        area: ['430px', '120px'],
        title: '',
        shade: 0.3, //遮罩透明度
        moveType: 1, //拖拽风格，0是默认，1是传统拖动
        shift: 6, //0-6的动画形式，-1不开启
        content: '<div style="padding-left: 15px;padding-top: 20px;">' + content + '</div>'
    });
}
//询问框
function AlertMsgBoxWithFunction(title, content, firstbtnstr, secondbtnstr, firstfunction, secondfunction) {
    var showfirstbtn = true;
    var showseconbtn = true;
    var btnarry = [];
    if (title == "" || typeof (title) == "undefined" || title == null) {
        title = "title";
    }
    if (content == "" || typeof (content) == "undefined" || content == null) {
        content = "Empty";
    }
    if (firstbtnstr == "" || typeof (firstbtnstr) == "undefined" || firstbtnstr == null) {
        showfirstbtn = false;
    }
    else {
        btnarry.push(firstbtnstr);
    }
    if (secondbtnstr == "" || typeof (secondbtnstr) == "undefined" || secondbtnstr == null) {
        showseconbtn = false;
    }
    else {
        btnarry.push(secondbtnstr);
    }
    layer.confirm(content, {
        title: title,
        btn: btnarry //按钮
    }, firstfunction,
        secondfunction
    );
}
/**
 * alert Error box modify by nls 
 * @param {} content 
 */
function closepage() {
    var browserName = navigator.appName;
    if (browserName == "Netscape") {
        window.open('', '_self', '');
        window.close();
    }
    if (browserName == "Microsoft Internet Explorer") {
        window.parent.opener = "whocares";
        window.parent.close();
    }
}

function htmlEncode(value) {
    return !value ? value : String(value).replace(/&/g, "&amp;").replace(/\"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
}

function htmlDecode(value) {
    if (value && (value === '&nbsp;' || value === '&#160;' || (value.length === 1 && value.charCodeAt(0) === 160))) { return ""; }
    return !value ? value : String(value).replace(/&gt;/g, ">").replace(/&lt;/g, "<").replace(/&quot;/g, '"').replace(/&amp;/g, "&");
}

function encodeTextAreaString(str) {
    var reg = new RegExp("\n", "g");
    str = str.replace(reg, "<br/>");
    return str;
}
function decodeTextAreaString(str) {
    var reg = new RegExp("<br/>", "g");
    str = str.replace(reg, "\n");
    return str;
}

function FormatTextAreaValue(str) {
    return decodeTextAreaString(htmlDecode((str)));
}

function init(id) {
    var text = document.getElementById(id);
    text.style.height = 'auto';
    text.style.height = text.scrollHeight+ 'px';
}